# -*- coding: utf-8 -*-
from django import forms as f
from requests.models import Request
from requests.constants import ADD_REQUEST, EDIT_REQUEST, REMOVE_REQUEST, \
    APPROVED_REQUEST, REJECTED_REQUEST
from datetime import date

CHOICES_ACCEPT = (
    (APPROVED_REQUEST, _(u'Approve')),
    (REJECTED_REQUEST, _(u'Reject')) 
)

class CustomModelForm(f.ModelForm):
    def as_div(self):
        "Returns this form rendered as HTML <div>s."
        return self._html_output(u'<div>%(label)s %(errors)s%(field)s%(help_text)s</div>', u'<div>%s</div>', '</div>', u'<p class="cf"><em>%s</em></p>', False)

class RequestModForm(CustomModelForm):
    """
    A generic form to moderators approve/reject the request
    """
    accept = f.ChoiceField(choices=CHOICES_ACCEPT, label=_('Approve'), help_text=('Approve this changes?'));
    class Meta:
        model = Request
        fields = ['accept', 'mod_comment', ]
    #TODO: save...

class RequestForm(f.ModelForm):
    """
    A generic form to make the requests 
    
    Usage:
    class SomeForm(RequestForm):
    class Meta:
        model = m.SomeModel
    """
    _exclude = ['comment'] #Fields from the form that is not from the object 
    comment = f.CharField(widget=f.Textarea(), label=_('Personal comments to Moderators'), help_text=_('Your comments for the moderators.'), required=False)
    
    def save(self, type, user, **kwargs): # for form.save(commit=False) use form.create_instance()
        user_comment = self.cleaned_data.get('comment', '')
        if type == ADD_REQUEST:
            super(RequestForm, self).save(commit=False)
            self.isntance.request_add(user, user_comment)
        elif type == EDIT_REQUEST:
            data = {}
            for field in self.changed_data:
                if field not in self._exclude:
                    a = self.cleaned_data[field]
                    if hasattr(a, 'pk'):
                        data[field] = a.pk
                    else:
                        if isinstance(a, date):
                            data[field] = unicode(a)
                        else:
                            data[field] = a
            self.instance.request_edit(data, user, user_comment)
        elif type == REMOVE_REQUEST:
            self.instace.request_remove(user, user_comment)
            
    def exclude_field(self, *args):
        "Ignore the specified fields from the form.changed_data"
        self._exclude.extend(args)
        
    def unexclude_field(self, field):
        "Don't ignore the specified field from the form.changed_data"
        try:
            self._exclude.remove(field)
        except ValueError:
            pass